package com.bwie.house.service.impl;

import com.alibaba.fastjson.JSON;
import com.bwie.house.entity.FlatsEntity;
import com.bwie.house.vo.ResoldSearchVo;
import com.bwie.house.vo.ResoldVo;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.house.dao.ResoldDao;
import com.bwie.house.entity.ResoldEntity;
import com.bwie.house.service.ResoldService;


@Service("resoldService")
public class ResoldServiceImpl extends ServiceImpl<ResoldDao, ResoldEntity> implements ResoldService {
    @Autowired
    RestHighLevelClient client;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ResoldEntity> page = this.page(
                new Query<ResoldEntity>().getPage(params),
                new QueryWrapper<ResoldEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils ResoldEsList(ResoldSearchVo resoldSearchVo) {
        SearchRequest searchRequest = new SearchRequest("resold");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();


        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //判断  二手房名称 不为空和空字符串
        if(StringUtils.isNotEmpty(resoldSearchVo.getResoldTitle()) ){
//            二手房名称模糊查找
            MatchQueryBuilder flats_name = QueryBuilders.matchQuery("resoldTitle", resoldSearchVo.getResoldTitle());
            boolQueryBuilder.must(flats_name);
        }

//        二手房地址
        if(StringUtils.isNotEmpty(resoldSearchVo.getResoldAddress())){
//            二手房地址模糊查找
            MatchQueryBuilder flats_address = QueryBuilders.matchQuery("resoldAddress", resoldSearchVo.getResoldAddress());
            boolQueryBuilder.must(flats_address);
        }

//        地区id(县id)
        if(resoldSearchVo.getXianId()!=null){
//             地区id(县id)
            TermQueryBuilder xianId = QueryBuilders.termQuery("xianId", resoldSearchVo.getXianId());
            boolQueryBuilder.must(xianId);
        }

//         private BigDecimal flatsAvgPrice1;
        if(resoldSearchVo.getResoldPrice1()!=null){
//            楼盘均价
            RangeQueryBuilder flatsAvgPrice = QueryBuilders.rangeQuery("resoldPrice").gte(resoldSearchVo.getResoldPrice1());
            boolQueryBuilder.must(flatsAvgPrice);
        }
//    private BigDecimal flatsAvgPrice2;
        if(resoldSearchVo.getResoldPrice2()!=null){
//            楼盘均价o
            RangeQueryBuilder flatsAvgPrice = QueryBuilders.rangeQuery("resoldPrice").lte(resoldSearchVo.getResoldPrice2());
            boolQueryBuilder.must(flatsAvgPrice);
        }

//         /**
//     * 装修情况（1 毛坯 2简装 3精装 4豪装）
//     */
//    private Integer decolate;
        if(resoldSearchVo.getDecolate()!=null){
//               * 装修情况（1 毛坯 2简装 3精装 4豪装）
            TermQueryBuilder decolate = QueryBuilders.termQuery("decolate", resoldSearchVo.getDecolate());
            boolQueryBuilder.must(decolate);
        }

        searchSourceBuilder.query(boolQueryBuilder);
//    //排序状态   0-默认  1-价格低到高  2-价格高到低  3-开盘时间 正  4-开盘时间  desc  不存在的字段
//    private Integer status=0;   //四种情况  else 0
        if(resoldSearchVo.getStatus()!=null){
//            1-价格低到高
            if(resoldSearchVo.getStatus()==1){
                searchSourceBuilder.sort("resoldPrice", SortOrder.ASC);
//                2-价格高到低
            }else if(resoldSearchVo.getStatus()==2){
                searchSourceBuilder.sort("resoldPrice", SortOrder.DESC);
            }else{
                //默认按照 id 升序
                searchSourceBuilder.sort("resoldId", SortOrder.ASC);
            }
        }
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            TotalHits totalHits = searchResponse.getHits().getTotalHits();
            Long value = totalHits.value;
            SearchHit[] hits = searchResponse.getHits().getHits();
            List<ResoldVo> collect = Arrays.stream(hits).map(h -> {
                ResoldVo resoldVo = JSON.parseObject(h.getSourceAsString(), ResoldVo.class);
                return resoldVo;
            }).collect(Collectors.toList());
            return new PageUtils(collect,value.intValue(),1,3);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



}